<?php
class NoticeIndexController  extends Zone_Action{
	public function indexAction(){
		$user_id = get_user_id();
		$user = $this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$user_id'");

		$this
			->Model->delete('notices',"
				`user_id`='$user_id'
				AND  DATE_ADD(`date`, INTERVAL 3 DAY)  < NOW()");
				
		$posts = $this
			->Model->fetchAll("SELECT `a`.*,`b`.`photo` as `created_by_photo`,
				`b`.`username` as `created_by_name`, 
				`b`.`is_deleted` as `created_is_deleted`
				FROM `notices` as `a`
				LEFT JOIN `users` as `b` 
				ON `b`.`ID`=`a`.`created_by_id`
				WHERE 
					`user_id`='$user_id' 
					 ORDER BY `date` DESC");	
			
		$this->set('posts',$posts);
		$this->removeLayout();

		//update	
		$this->Model->update('notices',array(
			is_read	=> '1'
		),"`user_id`='$user_id' 
			AND `date` < '{$user['date_login']}'
			AND `is_read`='0'");	
	}
	
	public function emptyAction(){
		$user_id = get_user_id();
	}	

	public function checkAction(){
		$user_id = get_user_id();
		$user = $this->Model->fetchRow("SELECT * 
			FROM `users` WHERE `ID`='$user_id'");
		
		$data = array();
		
		//notice before login
		$num = $this
			->Model->fetchOne("SELECT COUNT(*) as q
				FROM `notices` 
				WHERE 
					`user_id`='$user_id' 
					AND `date`  < '{$user['date_login']}'
					AND `is_read`='0'");
		
		$data['num'] = $num;

		//get login notices
		$post = $this
			->Model->fetchRow("SELECT `a`.*,
					`b`.`photo` as `created_by_photo`,
					`b`.`username` as `created_by_name`
				FROM `notices` as `a`
				LEFT JOIN `users` as `b` 
				ON `b`.`ID`=`a`.`created_by_id`
				WHERE 
					`a`.`user_id`='0'
					AND `a`.`created_by_id`<>'$user_id'		
					AND `a`.`date` >= '{$user['date_login']}'
					AND  `a`.`date` >= '{$user['date_notice']}'");
		
		//get notices
		if( !$post ){
			$post = $this
				->Model->fetchRow("SELECT `a`.*,
						`b`.`photo` as `created_by_photo`,
						`b`.`username` as `created_by_name` 
					FROM `notices` as `a`
					LEFT JOIN `users` as `b` 
					ON `b`.`ID`=`a`.`created_by_id`
					WHERE
						`user_id`='$user_id' 
						AND `date` >= '{$user['date_login']}'
						AND `is_read`='0' LIMIT 1");
			if( $post ){			
				$this->Model->update('notices',array(
					is_read	=> '1'
				),"`ID`={$post['ID']}");
			}	
		}
		
		$this->Model->update('users',array(
			date_notice	=> new Model_Expr('NOW()')
		),"`ID`='$user_id'");
			
		$data['post'] = $post;	
		
		return $this->setContent(json_encode($data));
	}
	
	
	public function deleteAction(){
		$user_id = get_user_id();
		$id = getInt('ID',0);
		$this->Model->delete('notices',"`ID`='$id'");
		die('200');
	}
}	